﻿using System;
using System.Web.UI.WebControls;
using System.Web.Security;
using System.Web.Configuration;
using System.Web.UI;
using System.IO;
using System.Configuration;
using System.Collections;

public partial class System_Pages_Security_AccessRoles : SiteFox.Base.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        
    }
    protected void Page_PreRender()
    {
        rbl_Action_Value.SelectedIndex = 0;
        rbl_RuleAppliesTo_Value.SelectedIndex = 0;
        UserRoles.SelectedIndex = 0;
        UserList.SelectedIndex = 0;
        
        imb_Add.Visible = gv_Rules.Visible = false;

        if (rbl_SelectSoruce.SelectedValue == "System") 
        { 
            tv_System.Visible = true;
            tv_Web.Visible = false;
            if (tv_System.SelectedNode != null)
            {
                DisplayAccessRules(tv_System.SelectedValue);
                imb_Add.Visible = gv_Rules.Visible = true;
            }
        }
        else if (rbl_SelectSoruce.SelectedValue == "Web") 
        {
            tv_System.Visible = false;
            tv_Web.Visible = true;
            if (tv_Web.SelectedVirtualPath != "") 
            {
                DisplayAccessRules(tv_Web.SelectedVirtualPath);
                imb_Add.Visible = gv_Rules.Visible = true;
            }
        }
    }
    protected void Page_Init()
    {
        UserRoles.DataSource = Roles.GetAllRoles();
        UserRoles.DataBind();

        UserList.DataSource = Membership.GetAllUsers();
        UserList.DataBind();
    }

    protected void imb_Add_Click(object sender, ImageClickEventArgs e)
    {
        pan_Add.Visible = true;
    }
    protected void imb_Add_Close_Click(object sender, ImageClickEventArgs e)
    {
        pan_Add.Visible = false;
    }
    protected void lib_Add_Ok_Click(object sender, EventArgs e)
    {
        AuthorizationRule _NewRule;
        if (Convert.ToBoolean(rbl_Action_Value.SelectedValue))
        {
            _NewRule = new AuthorizationRule(AuthorizationRuleAction.Allow);
        }
        else 
        {
            _NewRule = new AuthorizationRule(AuthorizationRuleAction.Deny);
        }

        string _RuleToApply = rbl_RuleAppliesTo_Value.SelectedValue;
        if (_RuleToApply == "ApplyRole" && UserRoles.SelectedIndex > 0)
        {
            _NewRule.Roles.Add(UserRoles.Text);
            AddRule(_NewRule);
        }
        else if (_RuleToApply == "ApplyUser" && UserList.SelectedIndex > 0)
        {
            _NewRule.Users.Add(UserList.Text);
            AddRule(_NewRule);
        }
        else if (_RuleToApply == "ApplyAllUsers")
        {
            _NewRule.Users.Add("*");
            AddRule(_NewRule);
        }
        else if (_RuleToApply == "ApplyAnonUser")
        {
            _NewRule.Users.Add("?");
            AddRule(_NewRule);
        }
        
        pan_Add.Visible = false;
    }

    protected void DisplayAccessRules(string VirtualFolderPath)
    {
        Configuration _Config = WebConfigurationManager.OpenWebConfiguration(VirtualFolderPath);
        SystemWebSectionGroup _SystemWeb = (SystemWebSectionGroup)_Config.GetSectionGroup("system.web");
        AuthorizationRuleCollection _AuthorizationRules = _SystemWeb.Authorization.Rules;
        gv_Rules.DataSource = _AuthorizationRules;
        gv_Rules.DataBind();
    }

    protected void RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            AuthorizationRule _Rule = (AuthorizationRule)e.Row.DataItem;
            if (!_Rule.ElementInformation.IsPresent)
            {
                e.Row.Cells[3].Text = Resources.dcCommon.dc_InheritedFromHigherLevel;
                e.Row.Cells[4].Text = Resources.dcCommon.dc_InheritedFromHigherLevel;
            }
        }
    }
    protected string GetAction(AuthorizationRule Rule)
    {
        return Rule.Action.ToString();
    }
    protected string GetRole(AuthorizationRule Rule)
    {
        return Rule.Roles.ToString();
    }
    protected string GetUser(AuthorizationRule Rule)
    {
        return Rule.Users.ToString();
    }

    protected void DeleteRule(object sender, EventArgs e)
    {
        ImageButton _Button = (ImageButton)sender;
        GridViewRow _Item = (GridViewRow)_Button.Parent.Parent;
        string virtualFolderPath = "";
        if (rbl_SelectSoruce.SelectedValue == "System")
        {
            virtualFolderPath = tv_System.SelectedValue;
        }
        else if (rbl_SelectSoruce.SelectedValue == "Web") 
        {
            virtualFolderPath = tv_Web.SelectedVirtualPath;
        }
        Configuration config = WebConfigurationManager.OpenWebConfiguration(virtualFolderPath);
        SystemWebSectionGroup systemWeb = (SystemWebSectionGroup)config.GetSectionGroup("system.web");
        AuthorizationSection section = (AuthorizationSection)systemWeb.Sections["authorization"];
        section.Rules.RemoveAt(_Item.RowIndex);
        config.Save();
    }

    protected void MoveUp(object sender, EventArgs e)
    {
        MoveRule(sender, e, "up");
    }
    protected void MoveDown(object sender, EventArgs e)
    {
        MoveRule(sender, e, "down");
    }
    protected void MoveRule(object sender, EventArgs e, string UpOrDown)
    {
        UpOrDown = UpOrDown.ToLower();

        if (UpOrDown == "up" || UpOrDown == "down")
        {
            ImageButton _Button = (ImageButton)sender;
            GridViewRow _Item = (GridViewRow)_Button.Parent.Parent;
            int selectedIndex = _Item.RowIndex;
            if ((selectedIndex > 0 && UpOrDown == "up") || (UpOrDown == "down"))
            {
                string _SelectedVirtualPath = "";
                if (rbl_SelectSoruce.SelectedValue == "System")
                {
                    _SelectedVirtualPath = tv_System.SelectedValue;
                }
                else if (rbl_SelectSoruce.SelectedValue == "Web")
                {
                    _SelectedVirtualPath = tv_Web.SelectedVirtualPath;
                }
                Configuration _Config = WebConfigurationManager.OpenWebConfiguration(_SelectedVirtualPath);
                SystemWebSectionGroup _SystemWeb = (SystemWebSectionGroup)_Config.GetSectionGroup("system.web");
                AuthorizationSection _Section = (AuthorizationSection)_SystemWeb.Sections["authorization"];

                // Pull the local rules out of the authorization section, deleting them from same:
                ArrayList rulesArray = PullLocalRulesOutOfAuthorizationSection(_Section);
                if (UpOrDown == "up")
                {
                    LoadRulesInNewOrder(_Section, rulesArray, selectedIndex, UpOrDown);
                }
                else if (UpOrDown == "down")
                {
                    if (selectedIndex < rulesArray.Count - 1)
                    {
                        LoadRulesInNewOrder(_Section, rulesArray, selectedIndex, UpOrDown);
                    }
                    else
                    {
                        // DOWN button in last row was pressed. Load the rules array back in without resorting.
                        for (int x = 0; x < rulesArray.Count; x++)
                        {
                            _Section.Rules.Add((AuthorizationRule)rulesArray[x]);
                        }
                    }
                }
                _Config.Save();
            }
        }
    }

    protected void LoadRulesInNewOrder(AuthorizationSection Section, ArrayList RulesArray, int SelectedIndex, string UpOrDown)
    {
        AddFirstGroupOfRules(Section, RulesArray, SelectedIndex, UpOrDown);
        AddTheTwoSwappedRules(Section, RulesArray, SelectedIndex, UpOrDown);
        AddFinalGroupOfRules(Section, RulesArray, SelectedIndex, UpOrDown);
    }
    protected void AddFirstGroupOfRules(AuthorizationSection Section, ArrayList RulesArray, int SelectedIndex, string UpOrDown)
    {
        int adj;
        if (UpOrDown == "up") adj = 1;
        else adj = 0;
        for (int x = 0; x < SelectedIndex - adj; x++)
        {
            Section.Rules.Add((AuthorizationRule)RulesArray[x]);
        }
    }
    protected void AddTheTwoSwappedRules(AuthorizationSection Section, ArrayList RulesArray, int SelectedIndex, string UpOrDown)
    {
        if (UpOrDown == "up")
        {
            Section.Rules.Add((AuthorizationRule)RulesArray[SelectedIndex]);
            Section.Rules.Add((AuthorizationRule)RulesArray[SelectedIndex - 1]);
        }
        else if (UpOrDown == "down")
        {
            Section.Rules.Add((AuthorizationRule)RulesArray[SelectedIndex + 1]);
            Section.Rules.Add((AuthorizationRule)RulesArray[SelectedIndex]);
        }
    }
    protected void AddFinalGroupOfRules(AuthorizationSection Section, ArrayList RulesArray, int SelectedIndex, string UpOrDown)
    {
        int adj;
        if (UpOrDown == "up") adj = 1;
        else adj = 2;
        for (int x = SelectedIndex + adj; x < RulesArray.Count; x++)
        {
            Section.Rules.Add((AuthorizationRule)RulesArray[x]);
        }
    }
    protected ArrayList PullLocalRulesOutOfAuthorizationSection(AuthorizationSection Section)
    {
        ArrayList rulesArray = new ArrayList();
        for (int i = 0; i < Section.Rules.Count; i++) 
        {
            AuthorizationRule _Rule = Section.Rules[i];
            if (_Rule.ElementInformation.IsPresent)
            {
                rulesArray.Add(_Rule);
            }
        }

        // Next delete the rules from the section.
        for (int i = 0; i < rulesArray.Count; i++) 
        {
            AuthorizationRule _Rule = (AuthorizationRule)rulesArray[i];
            Section.Rules.Remove(_Rule);
        }

        return rulesArray;
    }
    protected void AddRule(AuthorizationRule NewRule)
    {
        string _SelectedVirtualPath = "";
        if (rbl_SelectSoruce.SelectedValue == "System") 
        {
            _SelectedVirtualPath = tv_System.SelectedValue;
        }
        else if (rbl_SelectSoruce.SelectedValue == "Web") 
        {
            _SelectedVirtualPath = tv_Web.SelectedVirtualPath;
        }
        
        Configuration _Config = WebConfigurationManager.OpenWebConfiguration(_SelectedVirtualPath);
        SystemWebSectionGroup _SystemWeb = (SystemWebSectionGroup)_Config.GetSectionGroup("system.web");
        AuthorizationSection _Section = (AuthorizationSection)_SystemWeb.Sections["authorization"];
        _Section.Rules.Add(NewRule);
        try
        {
            _Config.Save();
        }
        catch (Exception ex)
        {
            ucc_Add_Message.Value = ex.Message;
        }
    }
}